﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, double> setting = new Dictionary<string, double>();
            setting.Add("狗年生效酒", 0.02);
            setting.Add("窖藏1988", 0.05);
            setting.Add("金钻习酒", 0.08);
            setting.Add("蓝习酒", 0.1);
            setting.Add("老习酒", 0.12);
            setting.Add("品鉴酒", 0.20);
            setting.Add("空空如也", 0.80);


            List<string> list = getRandNumList(setting, 1);
            foreach (var item in list)
            {
                Console.WriteLine(item);
            }
            while (true) {
            };
        }

        /// <summary>
        /// 获取若干个不同随机数字
        /// </summary>
        /// <param name="setting">数字与出现概率的配置</param>
        /// <param name="num">获取数字个数</param>
        /// <returns></returns>
        static List<string> getRandNumList(Dictionary<string, double> setting, int num)
        {
            List<string> ret = new List<string>();
            for (int i = 0; i < num; i++)
            {
                if (setting.Count <= 0) break;
                string getKey = getRandNum(setting);   //获取单个随机数字
                setting.Remove(getKey); //从配置里去掉对应数字
                ret.Add(getKey);    //记录获取的数字
                System.Threading.Thread.Sleep(100); //随机数并不随机，不加这个随机数会比较连续
            }

            return ret;
        }

        /// <summary>
        /// 获取单个随机数字
        /// </summary>
        /// <param name="setting">数字与出现概率的配置</param>
        /// <returns></returns>
        static string getRandNum(Dictionary<string, double> setting)
        {
            double total = 0;
            Console.WriteLine("----------------概率区间");
            foreach (string key in setting.Keys)
            {
                total += setting[key];  //计算总概率值
                Console.WriteLine(key+"  "+total+"  "+setting[key]);
                
            }
            Console.WriteLine("----------------概率区间");
            Random rand = new Random();
            double r = rand.NextDouble() * total;   //取一个随机数，乘以总概率值，映射到总概率值的区间内
            Console.WriteLine("r:"+r+"  total:"+total);
            total = 0;
            foreach (string key in setting.Keys)
            {
                total += setting[key];  //按顺序累加概率值
                if (total > r)  //如果前面随机的数在对应区间内，则返回该数
                {
                    return key;
                }
            }

            return setting.Keys.Last<string>();    //返回最后一个数，对应rand.NextDouble()随机到1.0的情况
        }
    }
}
